package com.uniriho.setternumber

import java.util.Locale

object DataUtils {
    /**
     * 将byte数组转为16进制字符串
     *
     * @param bArr byte数组
     * @return 16进制字符串
     */
    fun bytesToHexString(bArr: ByteArray): String {
        val sb = StringBuffer(bArr.size)
        var sTmp: String
        for (i in bArr.indices) {
            sTmp = Integer.toHexString(0xFF and bArr[i].toInt())
            if (sTmp.length < 2) {
                sb.append(0)
            }
            sb.append(sTmp.uppercase(Locale.getDefault()))
        }
        return sb.toString()
    }

    /**
     * 16进制转Ascii
     * @param hexStr
     * @return
     */
    fun hexToAscii(hexStr: String): String {
        val output = StringBuilder("")
        var i = 0
        while (i < hexStr.length) {
            val str = hexStr.substring(i, i + 2)
            output.append(str.toInt(16).toChar())
            i += 2
        }
        return output.toString()
    }
}